package com.example.post.controller;

import com.example.post.Exception.ExceptionCodeMsgEnum;
import com.example.post.Exception.ServiceException;
import com.example.post.model.Blog;
import com.example.post.model.ResponseData;
import com.example.post.model.User;
import com.example.post.services.impl.UserServicesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class AdminController {

    @Autowired
    UserServicesImpl userServices;
    @GetMapping("/backendUser")
    @ResponseBody
    public ResponseData getBlog() {
        List userList=userServices.queryAll();
        ResponseData res;
        if (userList.isEmpty()){

            res = new ResponseData(500,"查询出错","");
            throw new ServiceException(ExceptionCodeMsgEnum.CONTENT_NOT_EXIST.getCode(), ExceptionCodeMsgEnum.CONTENT_NOT_EXIST.getMessage());

        }else{
            res = new ResponseData(200,"查询成功",userList);
        }
        return res;
    }

    @GetMapping("/users")
    @ResponseBody
    public ResponseEntity<List<User>> getPostsByTitle(@RequestParam String username) {
        List<User> users = userServices.findAllByUsername(username);
        if (users.isEmpty()) {

            return null;
        }
        return ResponseEntity.status(HttpStatus.OK).body(users);
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<String> updateUserpassWord(@PathVariable int id, @RequestBody User passwordRequest) {
        User user = userServices.getUserById(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        String password = passwordRequest.getPassword();
        userServices.updateUserById(id, password);
        return ResponseEntity.status(HttpStatus.OK).body("密码更改成功");
    }
    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUserById(@PathVariable int id) {
        User user = userServices.getUserById(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.status(HttpStatus.OK).body(user);
    }
}
